package com.youlai.boot.form.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.form.converter.FormCollectTaskConverter;
import com.youlai.boot.form.enums.TaskStatusConstant;
import com.youlai.boot.form.mapper.FormCollectTaskMapper;
import com.youlai.boot.form.model.entity.FormCollectTarget;
import com.youlai.boot.form.model.entity.FormCollectTask;
import com.youlai.boot.form.model.entity.FormDefinition;
import com.youlai.boot.form.model.form.FormCollectTaskForm;
import com.youlai.boot.form.service.FormCollectTargetService;
import com.youlai.boot.form.service.FormCollectTaskService;
import com.youlai.boot.form.service.FormDefinitionService;
import com.youlai.boot.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class FormCollectTaskServiceImpl extends ServiceImpl<FormCollectTaskMapper, FormCollectTask> implements FormCollectTaskService {

    private final FormCollectTaskConverter formCollectTaskConverter;
    private final FormCollectTargetService targetService;
    private final FormDefinitionService formDefinitionService;

    /**
     * 新增表单采集任务
     *
     * @param collectTaskForm
     * @return
     */
    @Override
    public Long save(FormCollectTaskForm collectTaskForm) {
        // 校验任务编码和任务名称是否存在
//        long count = this.count(new LambdaQueryWrapper<FormCollectTask>()
//                .eq(FormCollectTask::getTaskName, collectTaskForm.getTaskName())
//        );
//        if (count > 0){
//            throw new RuntimeException("任务名称已存在");
//        }
        // 实体转换
        FormCollectTask entity = formCollectTaskConverter.toEntity(collectTaskForm);

        // 校验表单是否存在
        FormDefinition formDefinition = formDefinitionService.getById(entity.getFormId());
        if (formDefinition == null){
            throw new RuntimeException("表单不存在");
        }
        if (formDefinition.getStatus() != 0 && formDefinition.getActive() != 0){
            throw new RuntimeException("表单未发布或未激活");
        }
        // 判断是否允许多次提交
        if (collectTaskForm.getAllowMultiSubmit() == 0){
            entity.setMaxSubmitCount(1);
        }
        entity.setCreateBy(SecurityUtils.getUserId());
        entity.setFormVersion(formDefinition.getVersion());
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String prefix = "TASK" + timestamp;
        entity.setTaskCode(prefix);
        // 保存并返回ID
        boolean result = this.save(entity);
        if (result) {
            return entity.getId(); // 返回新增记录的ID
        } else {
            throw new RuntimeException("保存失败");
        }
    }

    /**
     * 删除表单采集任务
     *
     * @param id
     * @return
     */
    @Override
    public Boolean delete(Long id) {
        // 判断任务是否已经提交
        FormCollectTask formCollectTask = this.getById(id);
        if (!Objects.equals(formCollectTask.getStatus(), TaskStatusConstant.DRAFT)) {
            throw new RuntimeException("任务已提交，请勿删除");
        }
        return this.removeById(id);

    }

    /**
     * 修改表单采集任务
     *
     * @param collectTaskForm
     * @return
     */
    @Override
    public Boolean edit(FormCollectTaskForm collectTaskForm) {
        // 判断任务是否已经提交
        FormCollectTask formCollectTask = this.getById(collectTaskForm.getId());
        if (!Objects.equals(formCollectTask.getStatus(), TaskStatusConstant.DRAFT)) {
            throw new RuntimeException("任务已提交，请勿修改");
        }
        FormCollectTask entity = formCollectTaskConverter.toEntity(collectTaskForm);
        FormDefinition formDefinition = formDefinitionService.getById(entity.getFormId());
        entity.setId(collectTaskForm.getId());
        entity.setUpdateBy(SecurityUtils.getUserId());
        entity.setFormVersion(formDefinition.getVersion());
        return this.updateById(entity);

    }

    /**
     * 提交表单采集任务
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Boolean publishTask(Long id) {
        // 根据任务id获取任务信息,并更新任务信息
        FormCollectTask entity = this.getById(id);
        if (entity == null){
            throw new RuntimeException("任务不存在");
        }
        if (!Objects.equals(entity.getStatus(), TaskStatusConstant.DRAFT)){
            throw new RuntimeException("任务已发布，请勿重复发布");
        };
        // 根据时间判断任务状态
        LocalDateTime now = LocalDateTime.now();
        int newStatus;
        if (now.isBefore(entity.getStartTime())) {
            // 当前时间在开始时间之前，设置为已发布
            newStatus = TaskStatusConstant.PUBLISHED;
        } else if (now.isAfter(entity.getEndTime())) {
            // 当前时间在结束时间之后，抛出异常
            throw new RuntimeException("当前时间在结束时间之前，请重新设置任务结束时间");
        } else {
            // 当前时间在任务期间内，设置为进行中
            newStatus = TaskStatusConstant.IN_PROGRESS;
        }
        
        // 更新任务状态
        entity.setStatus(newStatus);
        System.out.println("任务状态更新成功" + newStatus);
        List<FormCollectTarget> targetList = getFormCollectTargets(entity);
        if (CollectionUtils.isNotEmpty(targetList)){
             targetService.saveBatch(targetList);
        }
        return this.updateById(entity);
    }

    @NotNull
    private List<FormCollectTarget> getFormCollectTargets(FormCollectTask entity) {
        List<String> targetIds = List.of(entity.getTargetIds().split(","));
        List<FormCollectTarget> targetList = new ArrayList<>();
        targetIds.forEach(targetId -> {
            // 创建任务参与者
            FormCollectTarget target = new FormCollectTarget();
            target.setTaskId(entity.getId());
            target.setTargetId(Long.valueOf(targetId));
            // todo 通过用户id 获取用户名
            // target.setTargetName(userService.getById(targetId).getUsername());
            target.setSubmitStatus(0);
            target.setSubmitCount(0);
            target.setLastSubmitTime(null);
            targetList.add( target);
        });
        return targetList;
    }

    /**
     * 生成简单的任务编码
     * 格式: TASK + 年月日 + 4位序列号 (例如: TASK202511140001)
     *
     * @return 唯一的任务编码
     */
    public String generateTaskCode() {
        String datePart = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String prefix = "TASK" + datePart;

//        // 查询当天已存在的最大编码
//        LambdaQueryWrapper<FormCollectTask> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.likeRight(FormCollectTask::getTaskCode, prefix)
//                .orderByDesc(FormCollectTask::getTaskCode)
//                .last("LIMIT 1");
//
//        FormCollectTask latestTask = this.getOne(queryWrapper);
//
//        int nextSeq = 1;
//        if (latestTask != null && latestTask.getTaskCode().length() >= prefix.length() + 4) {
//            try {
//                String seqStr = latestTask.getTaskCode().substring(prefix.length());
//                nextSeq = Integer.parseInt(seqStr) + 1;
//            } catch (NumberFormatException e) {
//                nextSeq = 1;
//            }
//        }
//
//        if (nextSeq > 9999) {
//            throw new RuntimeException("当日任务编码已达上限(9999)");
//        }

        return prefix;
    }
}
